'use client';

import { useEffect, useState } from 'react';
import { Button, Table, message, Tag, Pagination } from 'antd';
import { useUser } from '../../context/userContext';
import api from '../../utils/api';
import styles from '@/components/Font.module.css';

export default function UserManagementPage() {
    const [users, setUsers] = useState([]);
    const [totalUsers, setTotalUsers] = useState(0);
    const { user } = useUser();
    const accessToken = user? user.access_token : "";

    // 分页相关
    const [usersPage, setUsersPage] = useState(1);
    const [usersPageSize, setUsersPageSize] = useState(5);

    // 加载状态
    const [isLoading, setIsLoading] = useState(false);

    const fetchUsers = async (page = 1, limit = 10) => {
        if (!accessToken) {
            message.error('请先登录');
            return;
        }
        try {
            setIsLoading(true);
            const response = await api.get('/users/all', {
                params: { page, limit },
                headers: { Authorization: `Bearer ${accessToken}` }
            });
            if (!response.data ||!Array.isArray(response.data.uers)) {
                console.error('用户数据格式错误，uers 不是数组:', response.data);
            }
            setUsers(response.data.uers || []);
            setTotalUsers(response.data.total || 0);
        } catch (error) {
            console.log(error, '获取用户信息失败');
        } finally {
            setIsLoading(false);
        }
    };

    // 立即更新本地用户列表中的角色
    const updateUserRole = (userId, newRole) => {
        setUsers(prevUsers => prevUsers.map(user => {
            if (user.uid === userId) {
                return { ...user, role: newRole };
            }
            return user;
        }));
    };

    const handleBanUser = async (userId) => {
        try {
            const response = await api.post(`/users/ban?id=${userId}`, undefined, {
                headers: {
                    Authorization: `Bearer ${accessToken}`
                }
            });
            if (response.status === 201) {
                message.success('用户封禁成功！');
                // 立即更新本地状态
                setUsers(prevUsers => prevUsers.map(user => {
                    if (user.uid === userId) {
                        return { ...user, status: 'banned' };
                    }
                    return user;
                }));
            }
        } catch (error) {
            console.log(error, '封禁用户出错');
        }
    };

    const handleUnbanUser = async (userId) => {
        try {
            const response = await api.post(`/users/unban?id=${userId}`, undefined, {
                headers: {
                    Authorization: `Bearer ${accessToken}`
                }
            });
            if (response.status === 201) {
                message.success('用户解封成功！');
                // 立即更新本地状态
                setUsers(prevUsers => prevUsers.map(user => {
                    if (user.uid === userId) {
                        return { ...user, status: 'active' };
                    }
                    return user;
                }));
            }
        } catch (error) {
            console.log(error, '解封用户出错');
        }
    };

    const handleAdmitUser = async (userId) => {
        try {
            const response = await api.post(`/users/admit?id=${userId}`, undefined, {
                headers: {
                    Authorization: `Bearer ${accessToken}`
                }
            });
            if (response.status === 200) {
                message.success('成功提升用户为管理员');
                // 立即更新本地状态
                updateUserRole(userId, 'admin');
            }
        } catch (error) {
            if (error.response && error.response.status === 403) {
                message.error('无权限');
            } else if (error.response && error.response.status === 404) {
                message.error('用户不存在');
            } else {
                console.log(error, '提升用户为管理员出错');
            }
        }
    };

    const handleUnadmitUser = async (userId) => {
        try {
            const response = await api.post(`/users/unadmit?id=${userId}`, undefined, {
                headers: {
                    Authorization: `Bearer ${accessToken}`
                }
            });
            if (response.status === 200) {
                message.success('成功撤销用户管理员权限');
                // 立即更新本地状态
                updateUserRole(userId, 'user');
            }
        } catch (error) {
            if (error.response && error.response.status === 403) {
                message.error('无权限');
            } else if (error.response && error.response.status === 404) {
                message.error('用户不存在');
            } else {
                console.log(error, '撤销用户管理员权限出错');
            }
        }
    };

    useEffect(() => {
        fetchUsers(usersPage, usersPageSize);
    }, [usersPage, usersPageSize]);

    const userPagination = {
        current: usersPage,
        pageSize: usersPageSize,
        total: totalUsers,
        onChange: (page, pageSize) => {
            setUsersPage(page);
            setUsersPageSize(pageSize);
            fetchUsers(page, pageSize);
        },
        // 禁用每页显示数量选择器
        showSizeChanger: false,
    };

    const userColumns =  [
        { 
            title: 'ID', 
            dataIndex: 'uid', 
            key: 'uid',
            className: styles.text,
            width: 80,
        },
        { 
            title: '用户名', 
            dataIndex: 'username', 
            key: 'username',
            className: styles.text,
            width: 120,
        },
        { 
            title: '邮箱', 
            dataIndex: 'email', 
            key: 'email',
            className: styles.text,
            width: 180,
        },
        { 
            title: '角色', 
            dataIndex: 'role', 
            key: 'role',
            className: styles.text,
            width: 100,
            render: (role) => (
                <Tag 
                    color={role === 'admin' ? '#D6A7A1' : '#C1B7B0'} 
                    style={{ 
                        fontFamily: 'var(--font-secondary)', 
                        fontSize: 14,
                        transition: 'all 0.3s ease' // 添加过渡动画
                    }}
                >
                    {role === 'admin' ? '管理员' : '普通用户'}
                </Tag>
            )
        },
        {
            title: '状态',
            dataIndex:'status',
            key:'status',
            className: styles.text,
            width: 100,
            render: (status) => (
                <Tag 
                    color={status === 'active' ? '#52c41a' : '#ff4d4f'} 
                    style={{ 
                        fontFamily: 'var(--font-secondary)', 
                        fontSize: 14,
                        transition: 'all 0.3s ease' // 添加过渡动画
                    }}
                >
                    {status === 'active' ? '正常' : '封禁'}
                </Tag>
            )
        },
        {
            title: '操作',
            key: 'action',
            className: styles.text,
            width: 380,
            render: (_, record) => (
                <div className="flex space-x-2">
                    <Button 
                        type="primary" 
                        className="bg-[#D6A7A1] hover:bg-[#E8D6D0] text-white rounded-md transition-all text-sm px-3 py-1.5"
                        onClick={() => handleBanUser(record.uid)}
                        disabled={record.status === 'banned'}
                    >
                        封禁
                    </Button>
                    <Button 
                        type="primary" 
                        danger 
                        className="bg-[#A3989D] hover:bg-[#C1B7B0] text-white rounded-md transition-all text-sm px-3 py-1.5"
                        onClick={() => handleUnbanUser(record.uid)}
                        disabled={record.status === 'active'}
                    >
                        解封
                    </Button>
                    <Button 
                        type="primary" 
                        className="bg-[#D6A7A1] hover:bg-[#E8D6D0] text-white rounded-md transition-all text-sm px-3 py-1.5"
                        onClick={() => handleAdmitUser(record.uid)}
                        disabled={record.role === 'admin'}
                    >
                        提升为管理员
                    </Button>
                    <Button 
                        type="primary" 
                        danger 
                        className="bg-[#A3989D] hover:bg-[#C1B7B0] text-white rounded-md transition-all text-sm px-3 py-1.5"
                        onClick={() => handleUnadmitUser(record.uid)}
                        disabled={record.role !== 'admin'}
                    >
                        撤销管理员权限
                    </Button>
                </div>
            )
        }
    ];

  return (
    <div className="bg-[#F4EDEB] rounded-2xl shadow-md p-6">
        <h2 className={`${styles.titlesmall} text-xl mb-6 text-[#7A6E6E]`}>用户管理</h2>
        <Table
            columns={userColumns}
            dataSource={users}
            pagination={false} // 关闭内置分页
            className="rounded-xl overflow-hidden bg-white"
            bordered={false}
            rowClassName={(record, index) => index % 2 === 0 ? 'bg-white' : 'bg-[#F4EDEB]/50'}
            size="middle"
            loading={isLoading}
            components={{
                header: {
                    cell: ({ className, ...restProps }) => (
                        <th
                            {...restProps}
                            className={`${className} ${styles.titlesmall} text-base font-semibold text-[#7A6E6E] bg-[#F4EDEB]`}
                        />
                    ),
                },
            }}
        />
        
        {/* 自定义分页组件 - 风格与整体设计保持一致 */}
        <div className="flex justify-center mt-6">
            <Pagination
                {...userPagination}
                className="bg-white p-3 rounded-lg shadow-sm flex items-center"
                itemRender={(current, type, originalElement) => {
                    if (type === 'page') {
                        return (
                            <a
                                className={`px-3 py-1.5 rounded-md mx-1 transition-all 
                                    ${current === usersPage ? 'bg-[#D6A7A1] text-white' : 'text-[#7A6E6E] hover:bg-[#F4EDEB]'}`}
                            >
                                {current}
                            </a>
                        );
                    }
                    if (type === 'prev') {
                        return (
                            <a
                                className={`px-3 py-1.5 rounded-md mx-1 transition-all 
                                    ${usersPage === 1 ? 'text-gray-400 cursor-not-allowed' : 'text-[#7A6E6E] hover:bg-[#F4EDEB]'}`}
                            >
                                <i className="fa fa-angle-left"></i>
                            </a>
                        );
                    }
                    if (type === 'next') {
                        return (
                            <a
                                className={`px-3 py-1.5 rounded-md mx-1 transition-all 
                                    ${usersPage === Math.ceil(totalUsers / usersPageSize) ? 'text-gray-400 cursor-not-allowed' : 'text-[#7A6E6E] hover:bg-[#F4EDEB]'}`}
                            >
                                <i className="fa fa-angle-right"></i>
                            </a>
                        );
                    }
                    return originalElement;
                }}
            />
        </div>
    </div>
  );
}